(function () {

    function CourseTable(trigger, config) {
        this.init(trigger, config);
    }

    /**
     * 在数组原形链添加shuffle方法
     * 随机打乱数组顺序
     */
    var addShuffle = function () {
        Array.prototype.shuffle = function () {
            var array = this;
            var m = array.length,
                t, i;
            while (m) {
                i = Math.floor(Math.random() * m--);
                t = array[m];
                array[m] = array[i];
                array[i] = t;
            }
            return array;
        }
    }();

    CourseTable.prototype = {
        constructor: CourseTable,
        init: function (trigger, config) {
            var _this = this;
            //行头
            _this.weeks = ['', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
            //列头
            _this.days = ['', '0102', '0304', '0506', '0708', '0910'];
            //课程背景颜色
            _this.colors = ['#00e079', '#ffc450', '#ff9dd8', '#86affe', '#59f0a3', '#ffa17d', '#d58dfb', '#81d0f7', '#4c8dae', '#3eede7', '#00ee00', '#4b5cc4', '#99ee00', '#f00056'];
            //课表内容数据
            _this.course = config.Course;
            //学期
            _this.term = _this.course[0].Date;
            //学号
            _this.stuId = _this.course[0].Student_id;
            //当前周
            _this.thisWeek = config.Current_week.toString();
            //绑定
            _this.trigger = trigger;
            //课表数组
            _this.courseArr = _this.createArray(6, 8, {});
            //渲染基本结构
            _this.renderStruct();
            //设置容器高度
            _this.setHeight();
            //设置当前周
            _this.setThisWeek();
            //填充数组
            _this.fillArr();
            //渲染课表内容
            _this.renderTabele();
            //创建mobieseletct  提供选择周数
            _this.createMobileSelect();
            //增添点击事件
            _this.addClick();
        },
        setThisWeek: function () {
            var _this = this;
            $('#current-week-btn #week').html(_this.thisWeek);
        },

        /**
         * 设置当前框架的高度为100%
         */
        setHeight: function () {
            var _this = this;
            $(_this.trigger).css('height', window.innerHeight);
        },

        /**
         * 填充课程数组数据
         */
        fillArr: function () {
            var _this = this;
            _this.initCourseArr();
            $.each(_this.course, function () {
                if (!_this.isEmptyObj(this)) {
                    if (_this.isCurrentWeek(this)) {
                        var i = $.inArray(this.Number, _this.days);
                        var j = $.inArray(this.Week, _this.weeks);
                        if (i != -1 && j != -1) {
                            _this.courseArr[i][j] = this;
                        }
                    }
                }
            });
        },

        /**
         * 初始化课程数组
         */
        initCourseArr: function () {
            var _this = this;
            for (var i = 0; i < _this.courseArr.length; i++) {
                for (var j = 0; j < _this.courseArr[i].length; j++) {
                    _this.courseArr[i][j] = {};
                }
            }
        },

        /**
         * 传入课程对象
         * 判断对象是否属于当前周
         * @param obj
         * @returns {boolean}
         */
        isCurrentWeek: function (obj) {
            var _this = this;
            var weekHave = obj.Weekhave;
            weekHave = weekHave.split(',');
            weekHave.splice($.inArray('', weekHave), 1);
            if ($.inArray(_this.thisWeek, weekHave) !== -1) {
                return true;
            } else {
                return false;
            }

        },

        /**
         * 渲染基本结构
         */
        renderStruct: function () {
            var _this = this;
            $(_this.trigger).append(
                '<div id="current-week">' +
                '<button id="current-week-btn" class="btn btn-info">' +
                '第<span id = "week"></span>周 ' +
                '</button>' +
                '</div>'
            );
            $(_this.trigger).append('<div id="timeTable"></div>');
            $(_this.trigger).append(
                '<div id="showContent" class="">' +
                '<div class="centerBox well"></div>' +
                '</div>'
            );
        },
        /**
         * 渲染课程表数据
         */
        renderTabele: function () {
            var _this = this;
            //初始化课程单元格背景颜色值
            _this.initBgColors();
            var result = '<table class="table table-responsive table-condensed">';
            for (var i = 0; i < _this.courseArr.length; i++) {
                if (i == 0) {
                    result += '<tr style="height:7%">';
                } else {
                    result += '<tr>';
                }
                for (var j = 0; j < _this.courseArr[i].length; j++) {
                    //处理第一行
                    if (i == 0) {
                        //加入周次
                        var cell = '<td class="weeks">' + _this.weeks[j] + '</td>';
                        result += cell;
                    } else if (i != 0 && j == 0) {
                        //加入节次
                        var num = '<td class="numbers">' + _this.renderNumebrs(_this.days[i]) + '</td>';
                        result += num;
                    } else {
                        //填充课程内容
                        var obj = _this.courseArr[i][j];
                        var cell = '<td onclick="javascript:courseTable.showDetails(' + i + ',' + j + ')">';
                        if (!_this.isEmptyObj(obj)) {
                            var bg = '<span class="add-color" style="background:' + _this.colors[_this.bgColors[obj.Course]] + ';" >';
                            cell += bg;
                            cell += '<span class="course">';
                            cell += _this.ifExceedLength(obj.Course, 8);
                            cell += '</span>';
                            cell += '<span class="position">@';
                            cell += _this.ifExceedLength(obj.Position, 9);
                            cell += '</span>';
                        }
                        cell += '</span></td>';
                        result += cell;
                    }
                }
                result += '</tr>';
            }
            result += '</table>';
            $('#timeTable').html(result);
        },

        /**
         * 将0102的课程节次分割
         * 通过slice方法 切割字符串
         * @param str
         * @returns {string}
         */
        renderNumebrs: function (str) {
            return "<p>" + str.slice(0, str.length / 2) + "</p><p>" + str.slice(str.length / 2, str.length) + "</p>";
        },

        /**
         * 判断某一字符串长度是否超过某定长
         * @param string 传入字符串
         * @param num 确定定长
         * @returns {*|string}
         */
        ifExceedLength: function (string, num) {
            var str = string.split('');
            var result = '';
            if (str.length > num) {
                result = string.substring(0, num - 1) + '..';
            } else {
                result = string;
            }
            return result;
        },

        /**
         * 判断对象是否为空
         * 将json对象转换为字符串数据  与 '{}'比较
         * @param obj 传入对象
         * @returns {boolean} 返回bool
         */
        isEmptyObj: function (obj) {
            return (JSON.stringify(obj) == '{}');
        },

        /**
         * 生成一个 row * col 数组
         * @param row 行
         * @param col 列
         * @param init_data 初始化数据
         * @returns {any[]}  返回数组
         */
        createArray: function (row, col, init_data) {
            var arr = new Array(row);
            for (var i = 0; i < arr.length; i++) {
                arr[i] = new Array(col);
                for (var j = 0; j < arr[i].length; j++) {
                    arr[i][j] = init_data;
                }
            }
            return arr;
        },

        /**
         * 初始化单元格颜色
         */
        initBgColors: function () {
            var _this = this;
            _this.bgColors = new Array();
            var i = 0;
            var indexArr = _this.makeArr(_this.colors.length);
            indexArr.shuffle();
            $.each(_this.course, function (index, obj) {
                if (!_this.bgColors[this.Course]) {
                    _this.bgColors[this.Course] = indexArr[i];
                    i++;
                }
            });
        },

        /**
         * 展示详细课程数据
         * i , j为传入的当前课程索引
         * @param i
         * @param j
         */
        showDetails: function (i, j) {
            var _this = this;
            var obj = _this.courseArr[i][j];
            if (!_this.isEmptyObj(obj)) {
                var content = '<ul class="list-group"><li class="list-group-item text-center">课程详情 <span class="caret"></span></li>';
                content += '<li class="list-group-item"><span class="label label-primary">课程</span> ' + obj.Course + '</li>';
                content += ' <li class="list-group-item"><span class="label label-success">班级</span> ' + obj.Class + '</li>';
                content += ' <li class="list-group-item"><span class="label label-info">时间</span> 第' + _this.thisWeek + '周,第' + obj.Number + '节</li>';
                content += ' <li class="list-group-item"><span class="label label-warning">地点</span> ' + obj.Position + '</li>';
                content += ' <li class="list-group-item"><span class="label label-danger">教师</span> ' + obj.Teacher + '</li></ul>';
                $('#showContent .centerBox').html(content);
                $('#showContent').fadeIn(650);
            }
        },

        /**
         * 添加点击事件
         */
        addClick: function () {
            $('#showContent').on('click', function (e) {
                $(this).fadeOut(400);
            });
        },

        /**
         * 使用mobileSelect插件 实现选择周数功能
         */
        createMobileSelect: function () {
            var _this = this;
            var weekArr = _this.createWeekArr();
            _this.mobileSelect = new MobileSelect({
                trigger: '#current-week-btn',
                title: '选择周数',
                wheels: [{
                    data: weekArr
                }],
                position: [parseInt(_this.thisWeek) - 1],
                transitionEnd: function (indexArr, dataArr) {
                },
                callback: function (indexArr, dataArr) {
                    _this.thisWeek = _this.getSelectedWeek(indexArr);
                    _this.fillArr();
                    _this.renderTabele();
                }
            });
        },

        /**
         * 获取选择周数
         * MobileSelect插件确定选择传入的是一个数组
         * 获取数组的第一个数据 即为选中周数
         * @param arr
         * @returns {*}
         */
        getSelectedWeek: function (arr) {
            return (arr[0] + 1).toString();
        },

        /**
         * 创建周数数组
         * @returns {any[]} 返回周数数组
         */
        createWeekArr: function () {
            var _this = this;
            var weekArr = new Array(30);
            var num = _this.makeArr(30);

            num.splice($.inArray(0, num), 1);
            if ($.inArray(30, num) == -1) {
                num.push(30);
            }
            for (var i = 0; i < weekArr.length; i++) {
                weekArr[i] = '第' + num[i] + '周';
            }
            return weekArr;
        },
        /**
         * 使用es6语法 生成到指定数的自然数数组
         * @param num 指定数
         * @returns {*} 返回数组
         */
        makeArr: function (num) {
            let f = length => Array.from({
                length
            }, (v, k) => k);
            return f(num);
        }
    }


    if (typeof exports == "object") {
        module.exports = CourseTable;
    } else if (typeof define == "function" && define.amd) {
        define([], function () {
            return CourseTable;
        })
    } else {
        window.CourseTable = CourseTable;
    }
})();